# -*- coding: utf-8 -*-

import sys
import time
import paramiko

ADDRESS = '123.125.45.247'
PORT = 9100
USERNAME = 'di'
PASSWORD = 'shUjUjIchENG'
FILE_PATH = r'D:\Company\fighterhit-tire-word-filter-master\tire-word-filter\target\\'
FILE_NAME = 'test.txt'
SCP_SHELL = r'scp ' + FILE_NAME + ' jr@10.136.16.37:~/project/tire-word-filter/lib\n'
SCP_PWD = '111111\n'

def ssh(address, port, username, password, cmd):
    passinfo = 'password: '
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(address, port, username, password)
    #stdin, stdout, stderr = ssh.exec_command('ls')
    #print stdout.readlines()
    channel = ssh.invoke_shell()
    channel.send(cmd)
    buff = ''
    while not buff.endswith(passinfo):
        try:
            resp = channel.recv(99999)
            print 'resp1', resp, '--------------'
        except Exception, e:
            print 'Error info:%s connection time.' % (str(e))
            channel.close()
            ssh.close()
            sys.exit()

        buff += resp
        if not buff.find('yes/no') == -1:
            channel.send('yes\n')
            buff = ''
    channel.send(SCP_PWD)
    print 'enter password'
    buff = ''
    while not buff.endswith("$ "):
        resp = channel.recv(99999)
        if not resp.find(passinfo) == -1:
            print 'Error info: Authentication failed.'
            channel.close()
            ssh.close()
            sys.exit()
        else:
            print 'ok'

        buff += resp

    print buff
    stdin, stdout, stderr = ssh.exec_command('rm ' + FILE_NAME)

    channel.close()
    ssh.close()

def ftp(address, port, username, password, file_path, remote_name):
    t = paramiko.Transport((address, port))
    t.connect(username = username, password = password)
    sftp = paramiko.SFTPClient.from_transport(t)
    remotepath = '~'
    localpath = file_path
    sftp.put(localpath, remote_name)
    t.close()

if __name__ == '__main__':
    ftp(ADDRESS, PORT, USERNAME, PASSWORD, FILE_PATH + FILE_NAME, FILE_NAME)
    #time.sleep(2)
    ssh(ADDRESS, PORT, USERNAME, PASSWORD, SCP_SHELL)
